﻿using BackData;
using Domain.DTOs.RBAC;
using Domain.RBAC;
using Infratructure;
using MediatR;
using Team.API.Applocation.Command.Users;

namespace Team.API.Applocation.Handler.Users
{
    public class UpdateUserHandler : IRequestHandler<UpdateUserCommand, APIResult<UserDTO>>
    {
        private readonly IRepository<Usermodel> userRepository;

        private readonly IRepository<Rolemodel> roleRepository;

        private readonly IRepository<Departmentmodel> depRepository;

        public UpdateUserHandler(IRepository<Usermodel> userRepository, IRepository<Rolemodel> roleRepository, IRepository<Departmentmodel> depRepository)
        {
            this.userRepository = userRepository;
            this.roleRepository = roleRepository;
            this.depRepository = depRepository;
        }

        public async Task<APIResult<UserDTO>> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
        {
            var user = await userRepository.GetByIdAsync(request.Id);
            if (user == null || user.IsDel)
            {
                return APIResult<UserDTO>.Faile("用户不存在");
            }

            user.Phone = request.Phone;
            user.Email = request.Email;
            //user.Updatedate = DateTime.Now;
            //user.Updatename = "系统管理员"; // TODO: 从当前登录用户获取

            int i = await userRepository.UpdateAsync(user);
            if (i <= 0)
            {
                return APIResult<UserDTO>.Faile("信息更改失败");
            }

            var role = await roleRepository.GetByIdAsync(user.RoleId);
            var dep = await depRepository.GetByIdAsync(user.DepartmentId);

            UserDTO userDTO = new UserDTO()
            {
                Id = user.Id,
                UserCode = user.UserCode,
                UserName = user.UserName,
                RealName = user.RealName,
                RoleId = user.RoleId,
                RoleName = role?.RoleName ?? string.Empty,
                DepartmentId = user.DepartmentId,
                DepartmentName = dep?.DepartmentName ?? string.Empty,
                Phone = user.Phone,
                Email = user.Email
            };

            return APIResult<UserDTO>.Ok("信息更改成功", userDTO);
        }
    }
}
